#include <iostream>
#include <string>

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>

#include "Socket.hpp"
#include "Protocol.hpp"
#include "InetAddr.hpp"

using namespace socket_n;

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        std::cout << argv[0] << "serve-ip serve-port" << std::endl;
        exit(0);
    }
    std::string severIp = argv[1];
    uint16_t severPort = std::stoi(argv[2]);

    // 1.创建socket链接远端服务器
    SockPtr socketPtr = std::make_shared<TcpSocket>();
    if (!socketPtr->CreatClientSocket(severIp, severPort))
    {
        std::cout << "creat or connect error" << std::endl;
        exit(1);
    }

    std::shared_ptr<Request> reqPtr = std::make_shared<Request>();
    std::shared_ptr<Response> resPtr = std::make_shared<Response>();
    std::string packageStream;
    while (true)
    {
        // 设置request
        reqPtr->_x = 888;
        reqPtr->_y = 1;
        reqPtr->_oper = '*';
        // 序列化
        std::string sendMessage;
        reqPtr->Serialize(sendMessage);
        // 添加报头
        sendMessage = EnCode(sendMessage);
        // 向套接字中写
        socketPtr->Send(sendMessage);
        while (true)
        {
            // 接收信息
            std::string recvMessage;
            ssize_t n = socketPtr->Recv(recvMessage);
            if (n <= 0)
                break;
            packageStream += recvMessage;
            // 提取一个完整的报文
            std::string jison = DeCode(packageStream);
            if (jison == "")
                continue;

            std::cout << "jison string: " << std::endl;
            std::cout << jison << std::endl;
            // 反序列化
            resPtr->Deserialize(jison);
            // 打印result
            std::cout << "result: " << resPtr->_result
                      << "code: " << resPtr->_code
                      << "describe: " << resPtr->_describe << std::endl;
        }
        sleep(2);
    }
    socketPtr->Close();

    return 0;
}